import subprocess
import socket
import threading
from ffmpeg import FFmpeg

class RtpReceiver:
    def __init__(self, port):
        self.port = port
        self.running = False
        self.process = None
        
    def start(self, output_file):
        self.process = (
            FFmpeg()
            .input(f"rtp://0.0.0.0:{self.port}?timeout=30")
            .output(output_file, vcodec='copy', acodec='copy')
            .execute_async()
        )
        self.running = True
        self.logger.info(f"开始接收RTP流，端口: {self.port}")

    def stop(self):
        if self.process:
            self.process.terminate()
        self.running = False

class MediaHandler:
    def __init__(self, config):
        self.config = config
        self.receivers = {}
        
    def create_receiver(self, channel_id):
        """创建RTP接收器"""
        port = self._find_free_port()
        receiver = RtpReceiver(port)
        self.receivers[channel_id] = receiver
        return port
    
    def _find_free_port(self):
        """在配置范围内寻找空闲端口"""
        for port in range(*self.config['media']['rtp_port_range']):
            with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
                try:
                    s.bind(('', port))
                    return port
                except OSError:
                    continue
        raise RuntimeError("没有可用RTP端口")